package core

import (
	"fmt"
	ipUtils "gitee.com/lvshicong/blog/utils/ip"
	"github.com/lionsoul2014/ip2region/binding/golang/xdb"
	"github.com/sirupsen/logrus"
	"strings"
)

var Searcher *xdb.Searcher

func InitIpDb() {
	var dbPath = "init/ip2region.xdb"
	_searcher, err := xdb.NewWithFileOnly(dbPath)
	if err != nil {
		logrus.Panicln("IP数据库连接失败", err)
		return
	}
	Searcher = _searcher
}

func GetIpAddr(ip string) (region string) {
	//判断是否是内网地址
	if ipUtils.HasLocalIPAddr(ip) {
		return "内网地址"
	}

	region, err := Searcher.SearchByStr(ip)
	if err != nil {
		logrus.Warnf("未知的IP地址：%s", ip)
		return "未知的IP地址"
	}

	_addristL := strings.Split(region, "|")
	if len(_addristL) != 5 {
		logrus.Warnf("异常的IP地址：%s", ip)
		return "异常的IP地址"
	}
	countries := _addristL[0]
	provinces := _addristL[2]
	city := _addristL[3]

	if provinces != "0" && city != "0" {
		return fmt.Sprintf("%s-%s", provinces, city)
	}
	if countries != "0" && provinces != "0" {
		return fmt.Sprintf("%s-%s", countries, provinces)
	}
	if countries != "0" {
		return countries
	}

	//中国 | 0 | 北京 | 北京市 | 联通
	return region
}
